package com.xinxing.city.recoverycheck;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.signature.ObjectKey;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.proembed.service.MyService;
import com.tbruyelle.rxpermissions3.Permission;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.xinxing.city.recoverycheck.databinding.ActivityMainBinding;
import com.xinxing.city.recoverycheck.entitys.KernelAction;
import com.xinxing.city.recoverycheck.entitys.KernelActions;
import com.xinxing.city.recoverycheck.entitys.WeightUp;
import com.xinxing.city.recoverycheck.interfaces.ICallBackWeight;
import com.xinxing.city.recoverycheck.interfaces.IDeviceKernel;
import com.xinxing.city.recoverycheck.interfaces.IRfidManager;
import com.xinxing.city.recoverycheck.interfaces.ISerialSendReceiveData;
import com.xinxing.city.recoverycheck.sdk_ttys.DecodeAc;
import com.xinxing.city.recoverycheck.ui.SettingActivity;
import com.xinxing.city.recoverycheck.util.SimplePreviewBig;
import com.xinxing.city.recoverycheck.util.VideoSet;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

import ZtlApi.ZtlManager;
import io.reactivex.rxjava3.functions.Consumer;


public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    private IDeviceKernel deviceKernel;
    private ISerialSendReceiveData sendReceiveData;
    private IRfidManager manager;
    private long weight = 0;
    private SimplePreviewBig simplePreview;
    public static VideoSet videoSet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        deviceKernel = DI.getInstance(IDeviceKernel.class);
        deviceKernel.start(this);
        sendReceiveData = deviceKernel.getSerial();
        manager = deviceKernel.getRfid();
        videoSet = new VideoSet(this);
        EventBus.getDefault().register(this);
        if (Constant.FACTORY == Constant.XIAOZHI) {
            binding.factoryName.setText("金牛星");
            ZtlManager.GetInstance().setContext(MainActivity.this);
            String deviceID = ZtlManager.GetInstance().getDeviceID();
            DecodeAc.DecodeAcPacket1();
            binding.btnZip.setVisibility(View.VISIBLE);
            binding.sn.setText("SN：" + deviceID);
            binding.factoryName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(MainActivity.this,SettingActivity.class);
                    startActivity(intent);
                }
            });
        } else if (Constant.FACTORY == Constant.CHENGKAI) {
            binding.factoryName.setText("成开");
            MyService mXService =
                    new MyService(this);
            String deviceID = mXService.getSerial();
            binding.sn.setText("SN：" + deviceID);
            binding.btnZip.setVisibility(View.GONE);
        } else {
            binding.factoryName.setText("智研院");
            String deviceID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
            binding.sn.setText("SN：" + deviceID);
            binding.btnZip.setVisibility(View.GONE);
        }

        binding.check.setOnClickListener(view -> {
            removeMessages();
            sendReceiveData.openDoor(1);
            if (Constant.FACTORY == 0) {
                binding.sendData.setText("aaac010000000000000000000000f7e3c90500ee79050000110001964b71d3a305d7d971167835924700027f520a");
            } else {
                binding.sendData.setText("0007110101b521");
            }

            mHandler.sendEmptyMessageDelayed(1, 10000);
//            mHandler.sendEmptyMessageDelayed(9, 1000);

        });
        binding.btnZip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendReceiveData.openZip(1);
            }
        });
        initPermission();

    }

    Handler
            mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1://关交投门
                    sendReceiveData.closeDoor(1);
                    if (Constant.FACTORY == Constant.XIAOZHI) {
                        binding.sendData1.setText("aaac010000000000000000000000f7e3c90500ee79090000010001f4bf0a");
                    } else {
                        binding.sendData1.setText("000711010074e1");
                    }
                    mHandler.sendEmptyMessageDelayed(20, 1000);
                    mHandler.sendEmptyMessageDelayed(2, 10000);
                    break;
                case 2://电子秤

                    sendReceiveData.getWeight(1);
                    if (Constant.FACTORY == Constant.XIAOZHI) {
                        // binding.sendData2.setText("aaac010000000000000000000000f7e3c90500ee79090000010001f4bf0a");
                    } else {
                        binding.sendData2.setText("000713010114E1");
                    }
                    mHandler.sendEmptyMessageDelayed(3, 10000);
                    break;
                case 3://压缩
//                    if(Constant.FACTORY== Constant.XIAOZHI){
//                        sendReceiveData.openZip(1);
//                        mHandler.sendEmptyMessageDelayed(4, 3*60*1000);
//                    }else {
                        mHandler.sendEmptyMessageDelayed(4, 5000);
//                    }
                    break;
                case 4://开启清运门
                    sendReceiveData.openLock(1);
                    if (Constant.FACTORY == Constant.XIAOZHI) {
                        binding.sendCleanData.setText("aaac010000000000000000000000f7e3ca0e00a6d90b0000110001964b71d3a305d7d97116783592470002cb3e0a");
                        mHandler.sendEmptyMessageDelayed(20, 8000);
                    } else {
                        binding.sendCleanData.setText("0007110102f520");
                        mHandler.sendEmptyMessageDelayed(20, 1000);
                    }

                    mHandler.sendEmptyMessageDelayed(6, 10000);
                    break;
                case 6://桶内摄像头
                    if (Constant.FACTORY == Constant.XIAOZHI) {
                        binding.simplePreview.removeAllViews();
                        SimplePreviewBig.id = 0;
                        simplePreview = new SimplePreviewBig(MainActivity.this);
                        binding.simplePreview.addView(simplePreview);
                        Message msg2 = new Message();
                        msg2.what = 22;
                        msg2.obj = 1;
                        mHandler.sendMessageDelayed(msg2, 1000);
                        mHandler.sendEmptyMessageDelayed(7, 5000);
                    } else if (Constant.FACTORY == Constant.CHENGKAI) {
                        binding.simplePreview.removeAllViews();
                        SimplePreviewBig.id = 1;
                        simplePreview = new SimplePreviewBig(MainActivity.this);
                        binding.simplePreview.addView(simplePreview);
                        Message msg2 = new Message();
                        msg2.what = 22;
                        msg2.obj = 1;
                        mHandler.sendMessageDelayed(msg2, 1000);
                        mHandler.sendEmptyMessageDelayed(7, 5000);
                    }
                    break;
                case 7://桶外摄像头
                    if (Constant.INIT_HK && videoSet != null) {
                        videoSet.takePicture1(1, "");
                        Log.e("TTT","桶外摄像头    "+Constant.INIT_HK);
                    }
                    Log.e("TTT","桶外摄像头"+Constant.INIT_HK);
                    mHandler.sendEmptyMessageDelayed(8, 5000);
                    break;
                case 8://人脸摄像头
                    if (Constant.FACTORY == Constant.XIAOZHI) {
                        binding.simplePreview.removeAllViews();
                        SimplePreviewBig.id = 1;
                        simplePreview = new SimplePreviewBig(MainActivity.this);
                        binding.simplePreview.addView(simplePreview);
                        Message msg3 = new Message();
                        msg3.what = 22;
                        msg3.obj = 2;
                        mHandler.sendMessageDelayed(msg3, 1000);
                    } else if (Constant.FACTORY == Constant.CHENGKAI) {
                        binding.simplePreview.removeAllViews();
                        SimplePreviewBig.id = 0;
                        simplePreview = new SimplePreviewBig(MainActivity.this);
                        binding.simplePreview.addView(simplePreview);
                        Message msg3 = new Message();
                        msg3.what = 22;
                        msg3.obj = 2;
                        mHandler.sendMessageDelayed(msg3, 1000);
                    }
                    mHandler.sendEmptyMessageDelayed(10, 5000);
                    break;

                case 9://rfid
                    binding.llyDiglog.setVisibility(View.VISIBLE);
                    if(Constant.FACTORY == Constant.XIAOZHI)
                        manager.loopRfid();
                    else{
                        manager.singleRfid();
                        mHandler.sendEmptyMessageDelayed(24,100);
                    }
                    break;
                case 10://满溢
                    if(Constant.FACTORY == Constant.CHENGKAI) {
                        sendReceiveData.getState();

                    }else{
                        sendReceiveData.getWeight(1);
                    }
                    mHandler.sendEmptyMessageDelayed(11, 5000);
                    Log.e("main", "查询满溢状态");
                    break;
                case 11://网络
                    runPingIPprocess("sr.xxcrtc.com");
                    mHandler.sendEmptyMessageDelayed(9, 10000);
                    break;
                case 20:
                    if(Constant.FACTORY == Constant.CHENGKAI)
                        sendReceiveData.getState();
                    else{
                        sendReceiveData.getWeight(1);
                    }
                    break;
                case 21:

                    break;
                case 22:
                    int num = (int) msg.obj;
                    if (simplePreview != null) {
                        simplePreview.take(MainActivity.this, num);
                    }
                    break;
                case 23:
                    String s = (String) msg.obj;
                    binding.net.setText(s);
                    if (s.contains("ms"))
                        binding.netState.setText("自检正常");
                    break;
                case 24:
                    if(binding.llyDiglog.getVisibility() == View.VISIBLE) {
                        manager.singleRfid();
                        mHandler.sendEmptyMessageDelayed(24, 100);
                    }
                    break;
            }
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onKernelEvent(KernelAction kernelAction) {
        int actionType = kernelAction.getActionType();
        List<String> params = kernelAction.getActionParams();
        switch (actionType) {
            case KernelActions.R_OPEN_DOOR:
                Log.e("TTT","交投门开："+params.get(0));
                binding.recData.setText(params.get(0));
                binding.openDoorState.setText("设备自检正常");
                break;
            case KernelActions.R_CLOSE_DOOR:
                Log.e("TTT","交投门关："+params.get(0));
                binding.recData1.setText(params.get(0));
                binding.closeDoorState.setText("设备自检正常");
                break;
            case KernelActions.R_CLEAN_DOOR:
                Log.e("TTT","清运门开："+params.get(0));
                binding.recCleanData.setText(params.get(0));
                binding.cleanState.setText("设备自检正常");
                break;
            case KernelActions.R_WEIGHT:
                Log.e("TTT","重量"+params.size());
                if (params.size() >= 2) {
                    Log.e("TTT","重量  "+params.get(1));
                    binding.recData2.setText(params.get(0));
                    binding.chengState.setText(params.get(1));
                }
                break;
            case KernelActions.RFID_READ:

                upDataRf(getRfid());
                break;
            case KernelActions.R_0A_COLSE:
                binding.recData1.setText(params.get(0));
                binding.closeDoorState.setText("设备自检正常");
                break;
            case KernelActions.R_23_OVER:
                Log.e("TTT","dddd"+params.get(0));
                if (params.get(0).equals("1")) {
                    binding.overState.setText("已满溢");
                } else {
                    binding.overState.setText("未满溢");
                }
                break;
            case KernelActions.R_CLOSE_CLEAN_DOOR:
                params.get(0);
                binding.recCleanData2.setText(params.get(0));
                break;
            case KernelActions.R_IMAGE:
                Log.e("TTT", "TTT");
                String i = params.get(0);
                String path = params.get(1);
                if (i.equals("1")) {
                    File file = new File(path);
                    Glide.with(this)
                            .load(file)
                            .signature(new ObjectKey(System.currentTimeMillis()))
                            .diskCacheStrategy(DiskCacheStrategy.NONE) // 不使用磁盘缓存
                            .into(binding.image1);
                    binding.tongneiImage.setText("自检正常");

                } else if (i.equals("2")) {
                    File file = new File(path);
                    Glide.with(this)
                            .load(file)
                            .signature(new ObjectKey(System.currentTimeMillis()))
                            .diskCacheStrategy(DiskCacheStrategy.NONE) // 不使用磁盘缓存
                            .into(binding.image3);

                    binding.factImage.setText("自检正常");
                }
                break;
            case KernelActions.R_16_HEART:
                if (params.size() > 0) {
                    String jsn = params.get(0);
                    Log.e("TTT", "R_16_HEART->>>   " + params.get(0));
                    Gson gson = new Gson();
                    Type dev = new TypeToken<List<WeightUp>>() {
                    }.getType();

                    List<WeightUp> weightUps = gson.fromJson(jsn, dev);
                    for (WeightUp weight2 : weightUps) {
                        if (weight2.getDoorid() == 1) {
                            binding.chengState.setText(String.valueOf(weight2.getWeights()));
                            if (weight2.getCleanDoorState() == 1)
                                binding.cleanCloseState.setText("清运门开");
                            else {
                                binding.cleanCloseState.setText("清运门关");
                            }
                            if (weight2.getSpillRed() == 1) {
                                binding.overState.setText("已满溢");
                            } else {
                                binding.overState.setText("未满溢");
                            }
                        }
                    }

                }
                break;
            case KernelActions.RFID_READ_F:
                if(Constant.FACTORY == Constant.XIAOZHI)
                    manager.loopRfid();
                break;
            case KernelActions.STATE:

                if (params.size() >= 4) {
                    Log.e("TTT","满溢状态："+params.get(1));
                    if (params.get(1).equals("1")) {
                        binding.overState.setText("已满溢");
                    } else {
                        binding.overState.setText("未满溢");
                    }
                }

            case KernelActions.HK:
                String path2 = params.get(0);
                File file = new File(path2);
                Glide.with(this)
                        .load(file)
                        .signature(new ObjectKey(System.currentTimeMillis()))
                        .diskCacheStrategy(DiskCacheStrategy.NONE) // 不使用磁盘缓存
                        .into(binding.image2);
                binding.tongwaiImage.setText("自检正常");

                break;
            case KernelActions.R_COLSE_CLEAN://成开关清运门
                binding.cleanCloseState.setText("关门成功");
                if (params.size() > 0)
                    binding.recCleanData2.setText(params.get(0));
                break;
            case KernelActions.R_0C_CLEAN:

                if (params.size() > 0)
                    binding.recCleanData.setText(params.get(0));
                binding.cleanState.setText("清运门开");
                break;
            case KernelActions.R_42_ZIP:
                if (params.get(0).equals("1")) {
                    binding.zipState.setText("压缩机开");
                } else {
                    binding.zipState.setText("压缩机关");
                }
                break;
            case KernelActions.R_26_DOOR:
                if(params.size()>1){
                    if(params.get(1).equals("1")){
                        binding.openDoorState.setText("设备自检正常");
                        binding.recData.setText(params.get(0));
                    }else{
                        binding.closeDoorState.setText("设备自检正常");
                        binding.recData2.setText(params.get(0));
                    }

                }
                break;

        }
    }

    private void initPermission() {
        RxPermissions rxPermission = new RxPermissions(MainActivity.this);
        rxPermission
                .requestEach(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            // 用户已经同意该权限
                            if (permission.name.contains("android.permission.CAMERA")) {

                            }
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                            Log.d("TAG", permission.name + " is denied. More info should be provided.");
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            Log.d("TAG", permission.name + " is denied.");
                        }
                    }
                });

    }

    public void upDataRf(List<String> rfids) {
        for (String rfid : rfids) {
            Log.e("rfid","读到数据:  "+rfid);
            if (rfid.length() >= 12) {
//                String item = rfid.substring(12, rfid.length()).toUpperCase();
                binding.rfid.setText(rfid);
                binding.rifdState.setText("自检正常，读到RFID");
                binding.llyDiglog.setVisibility(View.GONE);
            }
            break;
        }
    }

    private List<String> getRfid() {
        return deviceKernel.getRfid().getRfid();

    }

    public void runPingIPprocess(final String ipString) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                String address = ipString;

                try {
                    InetAddress inetAddress = InetAddress.getByName(address);

                    Runtime runtime = Runtime.getRuntime();
                    Process process = runtime.exec("ping -c 4 " + inetAddress.getHostAddress());

                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    StringBuilder result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                    Message msg = new Message();

                    msg.what = 23;
                    msg.obj = result.toString();
                    mHandler.sendMessage(msg);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    public void removeMessages() {
        mHandler.removeMessages(1);
        mHandler.removeMessages(2);
        mHandler.removeMessages(3);
        mHandler.removeMessages(4);
        mHandler.removeMessages(5);
        mHandler.removeMessages(6);
        mHandler.removeMessages(7);
        mHandler.removeMessages(7);
        mHandler.removeMessages(8);
        mHandler.removeMessages(9);
        mHandler.removeMessages(10);
        mHandler.removeMessages(11);
        mHandler.removeMessages(20);
        mHandler.removeMessages(21);
        mHandler.removeMessages(22);
        mHandler.removeMessages(24);
        binding.openDoorState.setText("等待自检");
        binding.cleanState.setText("等待自检");
        binding.cleanCloseState.setText("等待自检");
        binding.chengState.setText("等待自检");
        binding.rifdState.setText("等待自检");
        binding.closeDoorState.setText("等待自检");
        binding.overState.setText("等待自检");
        binding.tongwaiImage.setText("等待自检");
        binding.tongneiImage.setText("等待自检");
        binding.factImage.setText("等待自检");
        binding.zipState.setText("等待自检");
        binding.netState.setText("等待自检");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeMessages();
        deviceKernel.stop();
        EventBus.getDefault().unregister(this);
    }
}